// src/services/index.js
import axios from 'axios'
import router from "@/router/index.js";

class APIService {


    constructor() {
        
        this.TOKEN = localStorage.getItem('token') || null
        this.baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
        
        this.client = axios.create({
            baseURL: this.baseURL,
            timeout: 60000,
            headers: {
                'Content-Type': 'application/json',
                'Authorization' : `Bearer ${this.TOKEN}`

            }
        })

        // 如果有token，则设置Authorization header
        if (this.TOKEN) {
            // this.client.defaults.headers.common['Authorization'] = `Bearer ${this.TOKEN}`
        }
        // 添加响应拦截器进行统一处理
        this.setupInterceptors()
    }

    // 设置拦截器
    setupInterceptors() {
        // 响应拦截器
        this.client.interceptors.response.use(
            (response) => {
                // 统一处理成功响应
                return Promise.resolve({
                    success: true,
                    data: response.data,
                    status: response.status
                })
            },
            (error) => {
                // 统一处理错误响应
                const errorMsg = this.handleError(error)
                return Promise.resolve({
                    success: false,
                    error: errorMsg,
                    status: error.response?.status
                })
            }
        )
    }

    // 统一错误处理
    handleError(error) {
        if (error.response) {
            // console.error(error.response)
            // 服务器返回错误状态码
            switch (error.response.status) {
                case 400:
                    return error.response.data.message || '请求参数错误'
                case 401:
                    localStorage.removeItem('isLoggedIn')
                    localStorage.removeItem('loginInfo')

                    // 添加提示和倒计时
                    this.showLogoutCountdown()
                // return error.response.data.message || '未授权，请重新登录'
                case 403:
                    return error.response.data.message || '拒绝访问'
                case 404:
                    return error.response.data.message || '请求资源不存在'
                case 500:
                    return error.response.data.message || '服务器内部错误'
                default:
                    return `请求失败: ${error.response.statusText}`
            }
        } else if (error.request) {
            // 网络错误
            return '网络连接异常'
        } else {
            // 其他错误
            return error.message || '未知错误'
        }
    }

// 显示登出倒计时提示
    showLogoutCountdown() {
        // 创建提示元素
        const countdownElement = document.createElement('div')
        countdownElement.style.cssText = `        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 4px;
        color: #856404;
        z-index: 9999;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    `

        let countdown = 3
        countdownElement.innerHTML = `登录已过期，${countdown}秒后自动跳转到登录页面...`
        document.body.appendChild(countdownElement)

        const countdownInterval = setInterval(() => {
            countdown--
            if (countdown > 0) {
                countdownElement.innerHTML = `登录已过期，${countdown}秒后自动跳转到登录页面...`
            } else {
                clearInterval(countdownInterval)
                document.body.removeChild(countdownElement)
                router.push('/login')
            }
        }, 1000)
    }

    setToken(token) {
        localStorage.setItem('token', token)
        this.TOKEN = token
        this.client.defaults.headers.common['Authorization'] = `Bearer ${this.TOKEN}`
        // 同时更新当前client的header（以防万一）
        this.client.defaults.headers['Authorization'] = `Bearer ${this.TOKEN}`
    }

    // 注册
    async register(params) {
        try {
            return await this.client.post('/register', params)
        } catch (error) {
            return error
        }
    }

    // 登录
    async login(params) {
        try {
            return await this.client.post('/login', params)
        } catch (error) {
            return error
        }
    }

    // 获取待翻译列表
    async todo(params) {
        try {
            return await this.client.get('/translation/todo', {params})
        } catch (error) {
            return error
        }
    }

    async user_trans_history(params) {
        try {
            return await this.client.get('/translation/history', {params})
        } catch (error) {
            return error
        }
    }

    // 保存翻译
    async translation(params) {
        try {
            return await this.client.put('/translation', params)
        } catch (error) {
            return error
        }
    }

    // 获取待翻译列表
    async publish() {
        try {
            return await this.client.get('/translation/publish')
        } catch (error) {
            return error
        }
    }

//     -------------------v2接口---------------

    // 获取file_ids
    async file_ids() {
        try {
            return await this.client.get('/translation_v2/file_ids')
        } catch (error) {
            return error
        }
    }
    // 获取原文和译文
    async detail(params) {
        try {
            return await this.client.get('/translation_v2/detail',{params})
        } catch (error) {
            return error
        }
    }

}

export default new APIService()
